import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 刘远望
 * Date: 2025-05-28
 * Time: 20:12
 */
class Solution {
    //哈希表写法
    public int totalFruit1(int[] fruits) {
        Map<Integer, Integer> hash = new HashMap<>();//统计窗口内水果的种类

        int ret = 0;
        for (int left = 0, right = 0; right < fruits.length; right++) {
            int in = fruits[right];
            hash.put(in, hash.getOrDefault(in, 0) + 1);//进窗口

            while (hash.size() > 2) {//判断
                int out = fruits[left];
                hash.put(out, hash.get(out) - 1);

                if (hash.get(out) == 0) {
                    hash.remove(out);
                }
                left++;//出窗口--判断
            }
            ret = Math.max(ret, right - left + 1);//更新结果
        }
        return ret;
    }

    //hash模拟数组实现
    public int totalFruit2(int[] fruits) {
        int n = fruits.length;
        int[] hash = new int[n];//水果种类的数字充当下标

        int ret = 0;
        int kinds = 0;//记录窗口内水果的种类
        for (int left = 0, right = 0; right < n; right++) {
            int in = fruits[right];
            if (hash[in] == 0) {
                kinds++;
            }
            hash[in]++;//进窗口

            while (kinds > 2) {//判断
                int out = fruits[left];
                hash[out]--;

                if (hash[out] == 0) {
                    kinds--;
                }
                left++;//出窗口--判断
            }
            ret = Math.max(ret, right - left + 1);//更新结果
        }
        return ret;
    }
}